package com.data.modules.ai.controller;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.io.resource.ResourceUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.data.common.api.vo.CrmResult;
import com.data.common.api.vo.Result;
import com.data.common.aspect.annotation.AutoLog;
import com.data.common.crm.entity.AdminDeptVo;
import com.data.common.entity.BasePage;
import com.data.common.system.base.controller.BootController;
import com.data.common.system.query.QueryGenerator;
import com.data.modules.ai.constant.AiRuleH5PropertyEnum;
import com.data.modules.ai.entity.AdminDeptBO;
import com.data.modules.ai.entity.AiRule;
import com.data.modules.ai.entity.AiRuleBO;
import com.data.modules.ai.service.IAiRuleService;
import com.data.modules.feign.AdminService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.List;
import java.util.Properties;
import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.Collectors;

/**
 * @Description: 自动化流程规则数据
 * @Author: data-boot
 * @Date: 2022-03-03
 * @Version: V1.0
 */
@Api(tags = "自动化流程规则数据")
@RestController
@RequestMapping("/ai/rule")
@Slf4j
public class AiRuleController extends BootController<AiRule, IAiRuleService> {

    @Autowired
    private IAiRuleService aiRuleService;

    @Autowired
    @Lazy
    private AdminService adminService;

    /**
     * 分页列表查询
     *
     * @param aiRule
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    @AutoLog(value = "自动化流程规则数据-分页列表查询")
    @ApiOperation(value = "自动化流程规则数据-分页列表查询", notes = "自动化流程规则数据-分页列表查询")
    @GetMapping(value = "/list")
    public Result<?> queryPageList(AiRule aiRule,
                                   @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                   @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                   HttpServletRequest req) {
        QueryWrapper<AiRule> queryWrapper = QueryGenerator.initQueryWrapper(aiRule, req.getParameterMap());
        Page<AiRule> page = new Page<AiRule>(pageNo, pageSize);
        LambdaQueryWrapper<AiRule> wrapper = queryWrapper.lambda().eq(AiRule::getLogicDel, 0);
        IPage<AiRule> pageList = aiRuleService.page(page, wrapper);
        return Result.OK(pageList);
    }

    /**
     * 添加 批量
     *
     * @param bo
     * @return
     */
    @AutoLog(value = "自动化流程规则数据-添加 批量")
    @ApiOperation(value = "自动化流程规则数据-添加 批量", notes = "自动化流程规则数据-添加 批量")
    @PostMapping(value = "/batchAdd")
    public Result<?> batchAdd(@RequestBody AiRuleBO bo) {
        log.info("自动化流程规则数据-添加 批量 json ={} ", JSONObject.toJSONString(bo));
        List<AiRule> list = bo.getCitys().stream().map(city -> {
            AiRule rule = new AiRule();
            rule.setTitle(bo.getTitle());
            rule.setCompany(bo.getCompany());
            rule.setCompanyId(bo.getCompanyId());
            rule.setSource(bo.getSource());
            rule.setCity(city.getCity());
            rule.setCityId(city.getCityId());
            rule.setCityCode(city.getCityCode());
            return rule;
        }).collect(Collectors.toList());
        aiRuleService.saveBatch(list);

        return Result.OK("添加成功！");
    }

    /**
     * 添加
     *
     * @param aiRule
     * @return
     */
    @AutoLog(value = "自动化流程规则数据-添加")
    @ApiOperation(value = "自动化流程规则数据-添加", notes = "自动化流程规则数据-添加")
    @PostMapping(value = "/add")
    public Result<?> add(@RequestBody AiRule aiRule) {
        aiRuleService.save(aiRule);
        return Result.OK("添加成功！");
    }

    /**
     * 编辑
     *
     * @param aiRule
     * @return
     */
    @AutoLog(value = "自动化流程规则数据-编辑")
    @ApiOperation(value = "自动化流程规则数据-编辑", notes = "自动化流程规则数据-编辑")
    @PutMapping(value = "/edit")
    public Result<?> edit(@RequestBody AiRule aiRule) {
        aiRuleService.updateById(aiRule);
        return Result.OK("编辑成功!");
    }

    /**
     * 通过id删除
     *
     * @param id
     * @return
     */
    @AutoLog(value = "自动化流程规则数据-通过id删除")
    @ApiOperation(value = "自动化流程规则数据-通过id删除", notes = "自动化流程规则数据-通过id删除")
    @DeleteMapping(value = "/delete")
    public Result<?> delete(@RequestParam(name = "id", required = true) String id) {
        aiRuleService.removeById(id);
        return Result.OK("删除成功!");
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @AutoLog(value = "自动化流程规则数据-批量删除")
    @ApiOperation(value = "自动化流程规则数据-批量删除", notes = "自动化流程规则数据-批量删除")
    @DeleteMapping(value = "/deleteBatch")
    public Result<?> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
        this.aiRuleService.removeByIds(Arrays.asList(ids.split(",")));
        return Result.OK("批量删除成功!");
    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    @AutoLog(value = "自动化流程规则数据-通过id查询")
    @ApiOperation(value = "自动化流程规则数据-通过id查询", notes = "自动化流程规则数据-通过id查询")
    @GetMapping(value = "/queryById")
    public Result<?> queryById(@RequestParam(name = "id", required = true) String id) {
        AiRule aiRule = aiRuleService.getById(id);
        if (aiRule == null) {
            return Result.error("未找到对应数据");
        }
        return Result.OK(aiRule);
    }

    /**
     * 导出excel
     *
     * @param request
     * @param aiRule
     */
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, AiRule aiRule) {
        return super.exportXls(request, aiRule, AiRule.class, "自动化流程规则数据");
    }

    /**
     * 通过excel导入数据
     *
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, AiRule.class);
    }

    /**
     * 模糊查询 主体列表
     *
     * @param companyName
     * @param deptType
     * @return
     */
    @ApiOperation(value = "模糊查询 主体列表", notes = "模糊查询 主体列表")
    @GetMapping("/queryDeptSubjectsPage")
    public Result<?> queryDeptSubjects(AdminDeptBO bo) {
        CrmResult<BasePage<AdminDeptVo>> page = adminService.queryDeptSubjectsPage(bo);
        return Result.ok(page.getData().convertToPage());
    }

    /**
     * 递归查询 某层级子集
     *
     * @param deptId
     * @param deptLevel
     * @return
     */
    @ApiOperation(value = "递归查询 某层级子集", notes = "递归查询 某层级子集")
    @GetMapping("/getChildDeptByDeptId")
    public Result<?> getChildDeptListByDeptId(AdminDeptBO bo) {
        CrmResult<BasePage<AdminDeptVo>> page = adminService.getChildDeptByDeptId(bo);
        return Result.ok(page.getData().convertToPage());
    }

    /**
     * 配置属性操作的一个缓存
     */
    private static ConcurrentHashMap<String, Object> map = new ConcurrentHashMap<>();

    @PostMapping("/getDefForProperties")
    @ApiOperation("配置属性 查询")
    public Object getProperties() {
        log.info("================ 配置属性 查询 =结果：{}", AiRuleH5PropertyEnum.def.name());
        if (CollectionUtil.isEmpty(map)) {
            InputStream stream = ResourceUtil.getStream(AiRuleH5PropertyEnum.def.getRemark());
            Properties properties = new Properties();
            try {
                properties.load(new InputStreamReader(stream, "utf-8"));
            } catch (IOException e) {
                log.info("异常", e);
            }
            String property = properties.getProperty(AiRuleH5PropertyEnum.def.getDesc());
            map.put(AiRuleH5PropertyEnum.def.name(), property);
        }
        return map.get(AiRuleH5PropertyEnum.def.name());

    }

    //保存前端修改
    @PostMapping("/saveAllRule")
    public Result<?> saveAllRule(HttpServletRequest request, HttpServletResponse response, String exceldata) throws IOException {
        //jsonExcel =columnConfiguration.getData();
        log.info("==save jsonExcel:{}", exceldata);
        JSONArray jsonArray = JSON.parseArray(exceldata);
        JSONObject jsonObject = jsonArray.getJSONObject(0);
        JSONArray celldata = jsonObject.getJSONArray("celldata");
        log.info("==save JSONArray jsonExcel:{}", celldata);
        this.aiRuleService.saveAiRuleByExcel(celldata);
        return Result.ok(true);
    }

}
